let Jwt = require('jsonwebtoken');
let WeChatServer = require('../server/weChat/weChatServer');
let UserDao = require('../dao/userDao');
const Crypto = require('crypto');
let images = require('images');
let request = require('request');
let fs = require('fs');
let wx_ticket = {ticket: "", dateTime: 0};
exports.getToken = function (params) {
    return new Promise(function (resolve, reject) {
        let requestToWeChatResult = {};
        let IsNewUser = "T";
        let signObj = {};
        let userInfo = {};
        WeChatServer.requestToWeChat({
            serviceCode: "GET_ACCESS_TOKEN",
            queryParams: {
                code: params.code
            }
        }).then(function (result) {
            console.log('=================token=================', result)
            requestToWeChatResult = result;
            return UserDao.queryUser(masterPool, requestToWeChatResult);
        }).then(function (result) {
            signObj = {
                "openid": requestToWeChatResult.openid,
                "access_token": requestToWeChatResult.access_token,
                "refresh_token": requestToWeChatResult.refresh_token,
                "expires_in": requestToWeChatResult.expires_in * 1000 + new Date().getTime(),
                "invalid_in": new Date().getTime() + 3 * 24 * 60 * 60 * 1000
            };
            console.log(signObj);
            if (result.length > 0)
                IsNewUser = "F";
            return WeChatServer.requestToWeChat({
                serviceCode: "GET_USER_INFO",
                queryParams: {
                    openid: requestToWeChatResult.openid,
                    access_token: requestToWeChatResult.access_token
                }
            });
        }).then(function (result) {
            // userInfo.NickName = result.nickname;
            // userInfo.HeadImgUrl = result.headimgurl;
            resolve({token: Jwt.sign(signObj, config.token_secret), IsNewUser: IsNewUser, UserInfo: result})
        }, reject)
    });
};
exports.getQRCode = function (params) {
    return new Promise(function (resolve, reject) {
        UserDao.queryUser(masterPool, params)
            .then(function (result) {
                weChatApi.createTmpQRCode(result[0].openid, 2592000, function (err, result) {
                    console.log("==getQRCode err==", err);
                    console.log("==getQRCode result==", result);
                    if (err)
                        return reject(err);
                    resolve(result);
                })
            });
    })
};
/**
 * 推送二维码分享图
 * @param params
 * @returns {Promise<any>}
 */
exports.getQRCodeImg = function (params) {
    let headImgUrl = __dirname + '/images/head/' + Date.now() + 'qr.png';
    let ewmUrl = __dirname + '/images/qr/' + Date.now() + 'qr.png';
    let resultUrl = __dirname + '/images/result/' + Date.now() + 'result.jpg';
    let headImg;
    return new Promise(function (resolve, reject) {
        // UserDao.queryUser(masterPool, params);
        getUserInfo(params.openid)
            .then(function (result) {
                return getQRcode(result, params.openid);
            })
            .then(function (result) {
                return getQRimages(result);
            })
            .then(function () {
                return RunCheckFileExists();
            })
            .then(function (resultUrl) {
                return uploadImg(resultUrl);
            })
            .then(function (result) {
                return sendImg(params.openid, result.media_id);
            })
            .then(resolve, reject)
    });

    /**
     * 获取用户详情
     * @param openid
     * @returns {Promise<any>}
     */
    function getUserInfo(openid) {
        return new Promise((resolve, reject) => {
            if (openid) {
                weChatApi.getUser({openid: openid, lang: 'en'}, function (err, result) {
                    if (err) {
                        reject(err)
                    } else {
                        headImg = result.headimgurl;
                        resolve();
                    }
                });
            } else {
                reject('获取用户信息失败');
            }

        })
    }

    /**
     * 获取二维码
     * @param result
     * @param openid
     * @returns {Promise<any>}
     */
    function getQRcode(result, openid) {
        return new Promise(function (resolve, reject) {
            weChatApi.createTmpQRCode(openid, 2592000, function (err, qrResult) {
                console.log("==getQRCode err==", err);
                console.log("==getQRCode result==", qrResult);
                if (err)
                    return reject(err);
                resolve(qrResult);
            })
        })
    }

    /**
     * 生成图片
     * @param result
     * @returns {Promise<any>}
     */
    function getQRimages(result) {
        return new Promise(function (resolve, reject) {
            console.log('headImg ====>', headImg);
            console.log('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + result.ticket);
            if(headImg){
                request(headImg)
                    .pipe(fs.createWriteStream(headImgUrl))
                    .on('close', function () {
                        request('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + result.ticket)
                            .pipe(fs.createWriteStream(ewmUrl))
                            .on('close', function () {
                                console.log('pic saved!', __dirname + '/images/muban.jpg');
                                images(__dirname + '/images/muban.jpg')
                                    .draw(images(ewmUrl).size(242), 627, 1552)
                                    .draw(images(headImgUrl).size(50), 723, 1648)
                                    .save(resultUrl, {
                                        quality: 80
                                    });
                                resolve();
                            });
                    });
            }else{
                request('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + result.ticket)
                    .pipe(fs.createWriteStream(ewmUrl))
                    .on('close', function () {
                        console.log('pic saved!', __dirname + '/images/muban.jpg');
                        images(__dirname + '/images/muban.jpg')
                            .draw(images(ewmUrl).size(242), 627, 1552)
                            .save(resultUrl, {
                                quality: 80
                            });
                        resolve();
                    });
            }

        });
    }

    function RunCheckFileExists() {
        return new Promise(function (resolve, reject) {
            return checkFileExists()
                .then(function (isExists) {
                    if (isExists === 2) {
                        return RunCheckFileExists();
                    } else {
                        resolve(resultUrl);
                    }
                })
        })
    }

    function checkFileExists() {
        return new Promise(function (resolve, reject) {
            fs.exists(resultUrl, function (exists) {
                if (exists) {
                    resolve(1);
                } else {
                    resolve(2);
                }
            });

        })
    }

    /**
     * 上传图片
     * @param filePath
     * @returns {Promise<any>}
     */
    function uploadImg(filePath) {
        return new Promise(function (resolve, reject) {
            weChatApi.uploadMedia(filePath, 'image', function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    console.log('uploadMedia==>', result);
                    fs.unlink(ewmUrl);
                    fs.unlink(resultUrl);
                    fs.unlink(headImgUrl);
                    resolve(result);
                }
            });
        })
    }

    /**
     * 发送图片
     * @param openid
     * @param media_id
     * @returns {Promise<any>}
     */
    function sendImg(openid, media_id) {
        return new Promise(function (resolve, reject) {
            weChatApi.sendText(openid, '分享下图到朋友圈，满32个人扫码首次关注，请在公众号里直接文字联系我们，获取VIP激活码。', function (err, result) {
                if (err) {
                    console.log('sendText==>', openid, media_id);
                } else {
                    console.log('sendText==>', result);
                }
            })
            weChatApi.sendImage(openid, media_id, function (err, result) {
                if (err) {
                    console.log('sendImage==>', openid, media_id);
                    reject(err);
                } else {
                    console.log('sendImage==>', result);
                    resolve(result);
                }
            });
        })
    }
};
exports.getWXConfig = function (params) {
    return new Promise(function (resolve, reject) {
        if (wx_ticket.ticket) {
            if (wx_ticket.dateTime > Date.now()) {
                getJsConfig(params)
                    .then(function (result) {
                        resolve(result)
                    })
            } else {
                getTicket()
                    .then(function () {
                        return getJsConfig(params);
                    })
                    .then(function (result) {
                        resolve(result)
                    })
            }
        } else {
            getTicket()
                .then(function () {
                    return getJsConfig(params);
                })
                .then(function (result) {
                    resolve(result)
                })
        }
        // let payParams = {
        //     appId: config.weChat.AppID,
        //     timeStamp: parseInt(new Date().getTime() / 1000, 0) + '',
        //     nonceStr: Math.random().toString(36).substr(2, 15)
        // };
        // payParams.signature = getSignature(payParams);
        // console.log("=payParams=", payParams);
        // resolve(payParams);
        // console.log(weChatApi.jsTicket);
        // weChatApi.getJsConfig({},function (err,result) {
        //     console.log("==getWXConfig err==", err);
        //     console.log("==getWXConfig result==", result);
        //     if(err)
        //         return reject(err);
        //     resolve(result);
        // })

    });

    function getJsConfig(option) {
        return new Promise(function (resolve, reject) {
            let jsParams = {
                timeStamp: parseInt(new Date().getTime() / 1000, 0) + '',
                nonceStr: Math.random().toString(36).substr(2, 15),
                jsapi_ticket: wx_ticket.ticket,
                url: option.url
            };
            jsParams.signature = getSignature(jsParams);
            jsParams.appId = config.weChat.AppID;
            console.log("===>", jsParams);
            resolve(jsParams);
        });

    }

    function getTicket() {
        return new Promise(function (resolve, reject) {
            weChatApi.getTicket(function (err, result) {
                if (err)
                    return reject(err);
                wx_ticket.ticket = result.ticket;
                wx_ticket.dateTime = Date.now() + 7000000;
                resolve();
            });
        });
    }
};

function getSignature(params) {
    let keyArray = [];
    let signatureStr = "";
    delete params.sign;
    for (let key in params) {
        keyArray.push(key);
    }
    keyArray.sort();
    for (let i in keyArray) {
        if (params[keyArray[i]] != null) {
            signatureStr += "&" + keyArray[i].toLowerCase() + "=" + params[keyArray[i]];
        }
    }
    // signatureStr += "key=" + config.weChatPay.PaySecret;
    console.log("=signatureStr=", signatureStr.substr(1));
    return Crypto.createHash("sha1").update(signatureStr.substr(1), 'utf8').digest("hex");
}

function getRandomString() {
    let chararray = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'L', 'K', 'J', 'H', 'G', 'F', 'D', 'S', 'A', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'];
    let result = "";
    for (let i = 0, l = 32 - result.length; i < l; i++) {
        let id = Math.ceil(Math.random() * 35);
        result += chararray[id];
    }
    return result;
}

